/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package common;

import java.io.IOException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author HoangHai
 */
public class AngouManager {

    private static final String KEY = "gawara776";
    private static final String ALGORITHM = "Blowfish";

    public String encrypt(String text) throws javax.crypto.IllegalBlockSizeException,
            java.security.InvalidKeyException, java.security.NoSuchAlgorithmException,
            java.io.UnsupportedEncodingException, javax.crypto.BadPaddingException, javax.crypto.NoSuchPaddingException {

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, generateKey());
        byte[] encrypted = cipher.doFinal(text.getBytes());
        BASE64Encoder base64 = new BASE64Encoder();
        return base64.encode(encrypted);

    }

    public String decrypt(String encrypted) throws javax.crypto.IllegalBlockSizeException,
            java.security.InvalidKeyException, java.security.NoSuchAlgorithmException,
            javax.crypto.BadPaddingException, javax.crypto.NoSuchPaddingException, IOException {

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, generateKey());
        BASE64Decoder base64 = new BASE64Decoder();
        byte[] decrypted = cipher.doFinal(base64.decodeBuffer(encrypted));
        return new String(decrypted);

    }

    private SecretKeySpec generateKey() {

        SecretKeySpec sksSpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
        return sksSpec;

    }
}
